package cn.calm.repaymentNotice.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import cn.calm.repaymentNotice.client.RepaymentNoticeException;

public class DateUtil {
	private static final String DATE_FORMAT_DB="yyyy-MM-dd";
	private static final String DATE_FORMAT_DISPLAY="yyyy年MM月dd日";
	private static SimpleDateFormat sdf = new SimpleDateFormat();

	public static String formatDB(Date date) throws RepaymentNoticeException {
		if(date==null){
			throw new RepaymentNoticeException("日期类型不可以为null");
		}
		sdf.applyPattern(DATE_FORMAT_DB);
		return sdf.format(date);
	}

	public static Date parseDB(String value) throws RepaymentNoticeException {
		if(value==null){
			return null;
		}
		try {
			sdf.applyPattern(DATE_FORMAT_DB);
			return sdf.parse(value);
		} catch (Exception e) {
			throw new RepaymentNoticeException(String.format("[%s]解析错误,请使用[%s]格式", value,DATE_FORMAT_DB));
		}
	}
	public static Date parse(String value,String format) throws RepaymentNoticeException {
		try {
			sdf.applyPattern(format);
			return sdf.parse(value);
		} catch (ParseException e) {
			throw new RepaymentNoticeException(String.format("[%s]解析错误,请使用[%s]格式", value,format));
		}
	}
	public static String formatDisplay(Date date) throws RepaymentNoticeException {
		if(date==null){
			throw new RepaymentNoticeException("日期类型不可以为null");
		}
		sdf.applyPattern(DATE_FORMAT_DISPLAY);
		return sdf.format(date);
	}

	public static Date parseDisplay(String value) throws RepaymentNoticeException {
		if(value==null){
			return null;
		}
		try {
			sdf.applyPattern(DATE_FORMAT_DISPLAY);
			return sdf.parse(value);
		} catch (ParseException e) {
			throw new RepaymentNoticeException(String.format("[%s]解析错误,请使用[%s]格式", value,DATE_FORMAT_DISPLAY));
		}
	}
	
	public static long subDays(Date date){
		Calendar today=Calendar.getInstance();
		today.set(Calendar.HOUR_OF_DAY, 0);
		today.set(Calendar.MINUTE, 0);
		today.set(Calendar.MILLISECOND, 0);
		today.set(Calendar.SECOND, 0);
		long sub=date.getTime()-today.getTimeInMillis();
		long days=sub/86400000;
		return days;
	}
}
